from sqlalchemy import text
from flask import Blueprint,request
from model.model import *
from tools.catch import redis_cli
import json
import arrow

goods = Blueprint('/goods',__name__,url_prefix='/goods')

#获取所有的种类
@goods.route('/goods',methods=['get'])
def cate_get():
    cate = Cate.query.all()
    cate_list = [{'id':i.id,'c_name':i.c_name}for i in cate]
    return cate_list

#获取单个种类下所有的商品
@goods.route('/cate_goods',methods=['get'])
def goods_get():
    id = request.args.get('id')
    try:
        good_data = Goods.query.filter_by(cate_id=id).all()
    except Exception as e:
        return f'{e}'
    goods_list = [{
        'g_name':i.g_name,
        'count_num':i.count_num,
        'countent':i.countent,
        'price':i.price
    }for i in good_data]
    return {'msg':'ok','code':200,'data':goods_list}

#获取所有的小料
@goods.route('/get_food',methods=['get'])
def food_get():
    food = Food.query.all()
    food_list = [{'id':i.id,'price':i.price}for i in food]
    return {'msg':'ok','data':food_list,'code':200}

#获取订单下所有的成品
@goods.route('/order',methods=['get'])
def order_get():
    id = request.args.get('id')
    try:
        order_data =Order.query.filter_by(goods_h_id=id).all()
    except Exception as e:
        return f'{e}'
    order_list = [{'id':i.id,'status':i.status,'count_price':i.count_price,'count_num':i.count_num,
                   'countent':i.countent}for i in order_data]
    return f'这个店铺所有的订单是{order_list}'

# 获取所有商家
@goods.route('/goods_h',methods=['get'])
def goods_h_get():
    goods_h = Goods_H.query.all()
    goods_h_list = [{'g_name':i.g_name,'g_addr':i.g_addr,'is_defalue':i.is_defalue}for i in goods_h]
    return {'msg':'ok','data':goods_h_list,'code':200}

# 生成购物车
@goods.route('/keeping_create',methods=['post'])
def keeping():
    uid = request.args.get('uid')
    good_data = dict(request.json)
    redis_cli.hset(f'keeping_{uid}',key=arrow.get().int_timestamp,value=json.dumps(good_data))
    return {'msg':'ok'}

# 查看购物车
@goods.route('/keeping_create',methods=['get'])
def keeping_get():
    uid = request.args.get('uid')
    data = redis_cli.hgetall(name=f'keeping_{uid}')
    return {k.decode('utf-8'):json.loads(v.decode('utf-8')) for k,v in data.items()}

# 删除购物车
@goods.route('/keeping_create',methods=['delete'])
def keeping_delete():
    uid = request.args.get('uid')
    key = request.args.get('key')
    redis_cli.hdel(f'keeping_{uid}',key)
    return 'ok'

# 生成订单
@goods.route('/order_create',methods=['post'])
def order_create():
    # uid = request.args.get('uid')
    # keeping = Keeping.query.filter_by(user_id=uid).all()
    # order = Order()
    # order.goofiness.extend([i.goofiness[0] for i in keeping])
    # nums = {i.goofiness[0].goods_id:i.num for i in keeping}
    # db.session.query(goods_goods_h)\
    # .filter(goods_goods_h.c.num != None) \
    # .update({goods_goods_h.c.num:goods_goods_h.c.num - nums[1]},
    #         synchronize_session="evaluate")
    # db.session.commit()
    uid = request.form.get('uid')
    goofin_id = request.form.get('goofin_id')
    if not all([uid,goofin_id]):
        return {'msg':'前端数据不完整','code':400}
    goofiness = Goofiness.query.filter_by(id=goofin_id).first()
    if not goofiness:
        return {'msg':'商家不存在','code':400}
    data = redis_cli.hgetall(name=f'keeping_{uid}')
    goofin = {k.json.loads(v) for k,v in data.items()}
    print('>>>>>>>>>>>>>>>.',goofin)
    price = 0
    for i in goofin:
        good = i.get('goods')
        food = i.get('food')
        order_price = sum(food) + good.get('price')
        price += order_price
    order = Order(status=goofiness.status,number=uid + goofin_id,goods_price=price,
                  goofiness_id=goofin_id,user_id=uid)
    db.session.add(order)
    db.session.commit()
    return {'msg':'订单创建成功','code':200}

#生成成品
@goods.route('/goofiness',methods=['POST'])
def goofiness():
    gid= request.json.get('goods')
    fid = request.json.get('food')
    num = request.json.get('num')
    print('..................',gid,fid,num)
    if not all([gid,fid,num]):
        return {'msg':'前端数据不完整','code':400}
    try:
        goofindess = [Goofiness(goods_id=gid) for _ in range(num)]
        [db.session.add(i) for i in goofindess]
        # 提交会话
        db.session.flush()
        print(goofindess[0].id)
        for i in fid:
            # 使用原始sql语句
            # INSERT INTO food_goofiness VALUES (1,1),(1,2)
            # INSERT INTO food_goofiness VALUES (2,1),(2,2)
            sql = "INSERT INTO food_goofiness VALUES"
            sql += ",".join([f'({i},{go.id})' for go in goofindess])
            print('=============',sql)
            db.session.execute(text(sql))
        db.session.commit()
        return {'msg':'添加成功','code':200}
    except Exception as e:
        print('==================',e)
        return {'msg':'添加失败','code':400}




